DecimalFormat numform = new DecimalFormat("0.00"); 
System.out.println( "Num = " + numform.format(13.456) );

Answer:

Num = 13.46

The complete 13 was produced, even though there was only one zero left of the decimal point. Two digits were output to the right of the decimal point, as requested. The last digit was rounded.

'0' Format Code

The format pattern 000.00 asks that a number be converted into 6 characters, three digits on the left of the decimal separator, a decimal separator, and two digits on the right. However, all the digits that make up the integer part of the number are output, regardless of the format pattern.

This table shows how some doubles are converted to strings (using the US locale) under the direction of various format patterns. The doubles are 64-bit patterns contained in some variable, but the table shows them written out as decimals.

value of double format pattern output string
123.456
"000.000"
"123.456"
123.456
"000.0"  
"123.5"
123.456
"000"    
"123"
89.008
"000.000"  
"089.008"
89.008
"0.00"     
"89.01"
89.008
"0."       
"89."

The quote marks are not part of the output string. They are there to show the limits of the string. (Examples in pages to come show output strings that include spaces.) This applet demonstrates this. Enter a number and a format pattern, then click the button. Don't use quotation marks in the format pattern.

A bad number or a bad format pattern will cause an error message to be displayed. But DecimalFormat is quite forgiving about errors in the format pattern and will accept many patterns, even slightly flawed ones. Experiment with spaces and negative numbers.

Characters in the format pattern other than 0 and , are output unchanged, but may appear in unexpected places.

QUESTION 10:

What does the following fragment write?

DecimalFormat numform = new DecimalFormat("000,000.00"); 
System.out.println( "Num = " + numform.format(98765.432) );

Copy and Paste from the question into the applet to answer this question. Don't include the quote marks in the format pattern.